package com.biu.billiards.utils;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.biu.billiards.config.BaseErrorEnum;
import com.biu.billiards.config.BaseException;
import com.biu.billiards.model.bo.DyGoods;
import com.biu.billiards.model.entity.Dy;
import com.biu.billiards.model.entity.Goods;
import com.biu.billiards.model.vo.dy.DyGoodsVo;
import com.biu.billiards.model.vo.mqtt.OpenBilliardsVo;
import com.biu.billiards.service.impl.GoodsServiceImpl;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


@Component
public class DyUtils {

    private static GoodsServiceImpl goodsService;
    @Resource
    private GoodsServiceImpl rcsGoodsService;

    @PostConstruct
    public void init(){
        goodsService = rcsGoodsService;
    }


//    public static void main(String[] args) {
//
//
//        String  accessToken =  getAccessToken("awiv7gqsais9164p","9d9745f7721149fec20e2c98a9957538");
//
//        // System.out.println(accessToken);
//        DyGoods dyGoods = preCode(accessToken,"101400858319650");
//
//        //店铺
//        //7291936902788155428
//
//        valid(accessToken,dyGoods.getVerifyToken(),"7291936902788155428",dyGoods.getEncryptedCode());
//
//
////        {"data":{"verify_results":
////            [{"order_id":"1013034321635221861",
////                    "origin_code":"101400858319650",
////                    "result":0,"verify_id":"7294082103816308747",
////                    "account_id":"7291929433957468160","certificate_id":"7293707357447716927",
////                    "code":"CgwIARDhJxjLLyABKAESLgosU5Bb3FryVQxxc7/yK6j3OqFJpN0NVgmZPMQlrhow2qN5gldk0j3pp1jn/LMaAA==",
////                    "msg":"履约成功"}],"error_code":0,"description":"success"},"extra":{"error_code":0,
////                "description":"success","sub_error_code":0,"sub_description":"",
////                "logid":"202310261004501DAD85BE7F40FB466AD8","now":1698285890}}
//
//
//    }


    public static String getAccessToken(String clientKey,String clientSecret) {


        String uri = "https://open.douyin.com/oauth/client_token/";

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_key", clientKey);
        paramMap.put("client_secret", clientSecret);
        paramMap.put("grant_type", "client_credential");

        String result= HttpUtil.post(uri, paramMap);


        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");


        return jsonObject.getString("access_token");



    }


    public static DyGoods preCode(String accessToken, String code) {

        String uri = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/";

        String result = HttpRequest.get(uri)
                .contentType("application/json")
                .header("access-token", accessToken)
                .form("code", code).execute().body();


        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
        String verifyToken = jsonObject.getString("verify_token");
        JSONArray certificates = jsonObject.getJSONArray("certificates");

        System.out.println("jsonObject");
        System.out.println(jsonObject);

        DyGoods dyGoods = new DyGoods();


        if (certificates==null || certificates.size()==0){

            System.out.println("空");
            return dyGoods;

        }


        String encryptedCode = certificates.getJSONObject(0).getString("encrypted_code");
        String skuId = certificates.getJSONObject(0).getJSONObject("sku").getString("sku_id");
        dyGoods.setVerifyToken(verifyToken);
        dyGoods.setSkuId(skuId);
        dyGoods.setEncryptedCode(Collections.singletonList(encryptedCode));




        return dyGoods;


    }


    public static Boolean valid(String accessToken, String verifyToken, String poiId, List encryptedCode) {



        String uri = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/verify/";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("verify_token",verifyToken);
        jsonObject.put("poi_id",poiId);
        jsonObject.put("encrypted_codes",encryptedCode);

//        JSONArray encryptedCodeArray = new JSONArray();
//        encryptedCodeArray.add("xxx");
//        jsonObject.put("encrypted_codes",encryptedCodeArray);
   //     System.out.println(jsonObject.toString());

        String result = HttpRequest.post(uri)
                .contentType("application/json")
                .header("access-token", accessToken)
                .body(jsonObject.toJSONString()).execute().body();


        System.out.println("result");
        System.out.println(result);

        JSONObject resultObject = JSONObject.parseObject(result).getJSONObject("data");

        System.out.println("resultObject");
        System.out.println(resultObject);



        if ("success".equals(resultObject.get("description"))){

            return true;
        }else {
            return false;
        }

    }


    public static OpenBilliardsVo dyValid2(DyGoodsVo dyGoodsVo) {

        Goods goods = goodsService.selectGoodsSku("123456");
        OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();

        openBilliardsVo.setGoodsId(goods.getGoodsId());
        openBilliardsVo.setBilliardsNumber(dyGoodsVo.getBilliardsNumber());
        openBilliardsVo.setDeviceNumber(dyGoodsVo.getDeviceNumber());
        openBilliardsVo.setBilliardsId(dyGoodsVo.getBilliardsId());
        openBilliardsVo.setOpen(1);
        openBilliardsVo.setShopId(dyGoodsVo.getShopId());
        openBilliardsVo.setHardwareId(dyGoodsVo.getHardwareId());

        return openBilliardsVo;



    }



    public static OpenBilliardsVo dyValid(DyGoodsVo dyGoodsVo, Dy dy) {

        System.out.println("dyGoodsVo");
        System.out.println(dyGoodsVo);

       // String  accessToken =  getAccessToken("awiv7gqsais9164p","9d9745f7721149fec20e2c98a9957538");

        String  accessToken =  getAccessToken(dy.getDyKey(),dy.getDySecret());

        // System.out.println(accessToken);

        DyGoods dyGoods = preCode(accessToken,dyGoodsVo.getCode());


        Goods goods = goodsService.selectGoodsSku(dyGoods.getSkuId());


        OpenBilliardsVo openBilliardsVo = new OpenBilliardsVo();


        if (goods!=null){


            int nowHour = LocalDateTime.now().getHour();

            if ( nowHour>=goods.getStartTime()  && nowHour+1<=goods.getEndTime()){

                openBilliardsVo.setGoodsId(goods.getGoodsId());
                openBilliardsVo.setBilliardsNumber(dyGoodsVo.getBilliardsNumber());
                openBilliardsVo.setDeviceNumber(dyGoodsVo.getDeviceNumber());
                openBilliardsVo.setBilliardsId(dyGoodsVo.getBilliardsId());
                openBilliardsVo.setOpen(1);
                openBilliardsVo.setShopId(dyGoodsVo.getShopId());
                openBilliardsVo.setHardwareId(dyGoodsVo.getHardwareId());

               // if (valid(accessToken,dyGoods.getVerifyToken(),"7291936902788155428",dyGoods.getEncryptedCode())){
                if (valid(accessToken,dyGoods.getVerifyToken(), dy.getDyPoiId(),dyGoods.getEncryptedCode())){

                    return openBilliardsVo;
                }else {
                    return null;
                }

            }else {

                throw new BaseException(BaseErrorEnum.goods_time_ERROR);

            }


        }else {

            throw new BaseException(BaseErrorEnum.goods_ERROR);

        }


    }



}
